package com.glsc.ngateway.amdoc.services;

import com.glsc.ngateway.amdoc.handler.DateUtils;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.TInterfaceAccessHistoryTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;


@Service
public class InterfaceService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${gateway.datasource.driver-class-name}")
    private String mysqlDriverName;

    @Value("${gateway.datasource.url}")
    private String databaseSqlUrl;

    @Value("${gateway.datasource.username}")
    private String databaseSqlUsername;

    @Value("${gateway.datasource.password}")
    private String databaseSqlPassword;

    public Connection getConnection() throws ClassNotFoundException, SQLException {
        Connection conn = null;        //连接
        Class.forName(mysqlDriverName); //执行驱动
        conn = DriverManager.getConnection(databaseSqlUrl, databaseSqlUsername, databaseSqlPassword); //获取连接
        return conn;
    }

    public void insertInterfaceHistory(TInterfaceAccessHistoryTable historyTable) {

        Connection conn = null;        //连接
        PreparedStatement pstmt = null;    //使用预编译语句
        try {
            conn = getConnection();
            String sql = "insert into t_interface_access_history_table(" +
                    "params ,interface_name, access_time, ip, url, account, cost_time ) " +
                    "values(?,?,?,?,?,?,?) "; //设置的预编译语句格式
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, historyTable.getParams());
            pstmt.setString(2, historyTable.getInterfaceName());
            pstmt.setString(3, String.valueOf(historyTable.getAccessTime()));
            pstmt.setString(4, historyTable.getIp());
            pstmt.setString(5, historyTable.getUrl());
            pstmt.setString(6, historyTable.getAccount());
            pstmt.setString(7, String.valueOf(historyTable.getCostTime()));
            pstmt.executeUpdate();
            logger.info("接口访问数据插入成功，接口名称为：" + historyTable.getInterfaceName() + ",访问时间为：" + DateUtils.getCurrentDate(DateUtils.formatSecond));
        } catch (Exception e) {
            logger.error("Error", e);

        } finally {
            try {
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();  //必须要关
            } catch (Exception e) {
            }
        }
    }
}
